package org.zachary.commonservice.controller;

import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.zachary.commonservice.entity.News;
import org.zachary.commonservice.entity.NewsDTO;
import org.zachary.commonservice.entity.Result;
import org.zachary.commonservice.service.NewsService;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/news")
public class NewsController {
    @Resource
    private NewsService newsService;
    @GetMapping("/list")
    @Operation(summary = "获取新闻列表")
    public Result<List<News>> getNewsList() {
        try {
            List<News> list = newsService.getAll();
            return Result.success(list);
        } catch (Exception e) {
            log.error("getNewsList has error", e);
            return Result.fail("获取新闻失败");
        }
    }

    @PostMapping("/add")
    public Result<String> addNews(@RequestBody NewsDTO news) {
        System.out.println(news);
        try{
            newsService.addNews(news);
            return Result.success("新闻新增成功");
        } catch (Exception e) {
            log.error("新增新闻失败，详情为：", e);
            return Result.fail("新增新闻失败");
        }
    }

    @GetMapping("/delete")
    public Result<String> deleteNews(@RequestParam("id") Integer id) {
        try{
            newsService.deleteNews(id);
            return Result.success("新闻删除成功");
        } catch (Exception e) {
            log.error("删除新闻失败，详情为：", e);
            return Result.fail("删除新闻失败");
        }
    }

    @PostMapping("/update")
    public Result<String> addNews(@RequestBody News news) {
        System.out.println(news);
        try{
            newsService.updateNews(news);
            return Result.success("新闻修改成功");
        } catch (Exception e) {
            log.error("修改新闻失败，详情为：", e);
            return Result.fail("修改新闻失败");
        }
    }

}
